package com.yanxin

import java.io.{ObjectInputStream, ObjectOutputStream}
import java.net.{ServerSocket, Socket}

class RPCServer {

  //处理注册消息
  private def handlerRegister(account:String,password:String):ResultMsg = {
    println(s"a register msg from client : account $account password $password")
    //Server处理完成后,将消息再传给Client
    ResultMsg("register success")
  }


  //处理心跳消息
  private def handlerHeartbeat(id:String,content:String):ResultMsg = {
    println(s"a heartbeat msg from client : id $id content $content")
    //Server处理完成后,将消息再传给Client
    ResultMsg("heartbeat success")
  }

  def bind(port:Int):Unit ={
    //创建一个ServerSocket
    val ss = new ServerSocket(port)
    //服务端与客户端建立连接
    val clientSocket: Socket = ss.accept()
    //获取输入流(读取)
    val ois: ObjectInputStream = new ObjectInputStream(clientSocket.getInputStream)
    //获取输出流(写入)
    val oos: ObjectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream)
    var flag = true
    while (flag){
      val msg: AnyRef = ois.readObject()
      val rmsg: RemoteMsg = msg.asInstanceOf[RemoteMsg]   //确定是RemoteMsg类型
      //进行模式匹配

      val result = rmsg match {             //这个result是Server接收到Client后进行处理后的结果
        case RegisterMsg(account,password) =>{
          handlerRegister(account,password)
        }
        case HeartBeatMsg(id,content) =>{
          handlerHeartbeat(id,content)
        }

      }
      //将上面处理后的结果result发回给client
      oos.writeObject(result)
      oos.flush()

    }

  }
}


object RPCServer {

  def main(args: Array[String]): Unit = {
    val server = new RPCServer
    server.bind(8888)
  }

}